package br.edu.fanor.agendaweb.controllers;

import java.io.IOException;
import java.util.List;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.edu.fanor.agenda.exception.DaoException;
import br.edu.fanor.agenda.services.TipoTelefoneSession;
import br.edu.fanor.agenda.vo.TipoTelefone;

@WebServlet(name="tipoTelefoneController", urlPatterns="/pages/manterTipoTelefone")
public class TipoTelefoneController extends HttpServlet{

	private static final long serialVersionUID = 6969410166363073511L;

	protected void service(HttpServletRequest request, HttpServletResponse response)
		throws IOException{
		
		if(request.getSession().getAttribute("error") != null)
			request.getSession().removeAttribute("error");
		if(request.getSession().getAttribute("info") != null)
			request.getSession().removeAttribute("info");
		
		TipoTelefoneSession session = new TipoTelefoneSession();
		
		try {
			
			if(request.getParameter("method") != null && request.getParameter("method").equals("excluir")){
				Integer id = Integer.parseInt(request.getParameter("id"));
				TipoTelefone tipo = session.listarPorId(id);
				session.excluir(tipo);
				request.getSession().setAttribute("info", "Excluido com sucesso");
				List<TipoTelefone> tipos = session.listarTodos();
				request.getSession().setAttribute("lista", tipos);
			} else {
				List<TipoTelefone> tipos = session.listarTodos();
				request.getSession().setAttribute("lista", tipos);
				request.getSession().setAttribute("info", "Listagem com sucesso");
			}
		} catch (DaoException e) {
			request.getSession().setAttribute("error", e.getMessage());	
			e.printStackTrace();
		} catch(Exception e){
			request.getSession().setAttribute("error", "Tente mais tarde!");
			e.printStackTrace();
		}
		
		response.sendRedirect("/Agenda-web/pages/listTipoTelefone.jsp");
		
	}

}
